//
// Created by yanhai on 2021/11/5.
//

#include "spare_queue.h"

void SpareQueue::Enqueue(SpareQueue::value_type *node)
{
    std::lock_guard<std::mutex> lock(mutex);

    /* more node in queue */
    if (this->top != nullptr) {
        node->lnext = this->top;
        this->top->lprev = node;
        this->top = node;
        /* only node */
    } else {
        this->top = node;
        this->bot = node;
    }
    this->len++;
}

SpareQueue::value_type *SpareQueue::Dequeue()
{
    std::lock_guard<std::mutex> lock(mutex);

    value_type *node = this->bot;
    if (node == nullptr) {
        return nullptr;
    }

    /* more node in queue */
    if (this->bot->lprev != nullptr) {
        this->bot = this->bot->lprev;
        this->bot->lnext = nullptr;
        /* just the one we remove, so now empty */
    } else {
        this->top = nullptr;
        this->bot = nullptr;
    }

    if (this->len > 0)
        this->len--;

    node->lnext = nullptr;
    node->lprev = nullptr;
    return node;
}
